import { Controller } from "egg";
import { Result } from "../util/result";
import MsgEnum from "../util/msgEnum";
import xlsx from "node-xlsx";
import { get, isExistObject, put } from "../util/ossFile";
import RoleEnum from "../util/roleEnum";

const toArray = require('stream-to-array');

// import * as jwt from 'jsonwebtoken';
export default class FinancialController extends Controller {
  async getOrganizationChart() {
    const { ctx } = this;
    const results = await this.ctx.service.financial.getOrganizationChart();
    ctx.body = new Result(results);
  }
  async checkFinancial() {
    const { ctx } = this;
    // 参数验证

    const { financialCode } = ctx.query;

    const results = await this.ctx.service.financial.check(financialCode);
    ctx.body = new Result(results);
  }
  async getFinancial_list() {
    const { ctx } = this;
    // 参数验证
    ctx.validate(
      {
        page: { require, type: "int", convertType: "int" },
      },
      ctx.query
    );
    const { page, address, name, type } = ctx.query;

    const results = await this.ctx.service.financial.showFinancialList(
      page,
      address,
      type,
      name
    );
    ctx.body = new Result(results, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);
  }
  public async getFinancialMap() {
    const { ctx } = this;
    const data = await this.ctx.service.financial.getFinancialMap();
    if (data) {
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);
    } else {
      ctx.status = 400;
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);
    }
  }
  public async getMapsw() {
    const { ctx } = this;
    const data = await this.ctx.service.financial.getMapsw();
    if (data) {
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);
    } else {
      ctx.status = 400;
      ctx.body = new Result(data, MsgEnum.SERVER_ERROR);
    }
  }

  async deleteFinancial() {
    const { ctx, app } = this;
    // 参数验证
    app.validator.validate(
      {
        key: { require, type: "array" },
      },

      ctx.request.body
    );
    const { key } = ctx.request.body;
    const idNumberArray = key.map(Number);
    const results = await this.ctx.service.financial.deleteFinancial(idNumberArray);

    ctx.body = new Result(results, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);
  }

  async getSelectList() {
    const { ctx } = this;
    const results = await this.ctx.service.financial.showSelectList();
    ctx.body = new Result(results, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);
  }

  async updateFinancialFile() {
    const { ctx } = this;
    await ctx.getFileStream().then(async r => {
      const promise = await put(RoleEnum.ORGANIZATION, r.fields.id, r);
      if (promise.error) {
        ctx.status = 406;
        ctx.body = new Result(promise, MsgEnum.SERVER_ERROR);
      } else {
        ctx.body = new Result(promise, MsgEnum.UPLOAD_SUCCESS);
      }
    });
  }

  async getFinancialFile() {
    const { ctx } = this;

    const { id } = ctx.query;
    const result = await get(RoleEnum.ORGANIZATION, Number(id), ".pdf");
    if (result.error) {
      ctx.status = 406;
      ctx.body = result;
    } else {
      this.ctx.attachment(result.file_name);
      this.ctx.set("Content-Type", "application/octet-stream");
      ctx.body = result.result.stream;
    }
  }

  async updateFinancial() {
    const { ctx, app } = this;
    // 参数验证
    app.validator.validate(
      {
        id: { require, type: "string" },
        financialType: { require, type: "string" },
        financialName: { require, type: "string" },
        financialAddress: { require, type: "string" },
        creatTime: { require, type: "string" },
        invest: { require, type: "array" },
        contactPerson: { require, type: "string" },
        contactTel: { require, type: "string" },
        contactEmail: { require, type: "string" },

        description: { require, type: "string" },
      },
      ctx.request.body
    );
    const {
      id,
      creatTime,
      invest,
      financialType,
      financialAddress,
      financialName,
      contactPerson,
      contactTel,
      contactEmail,
      description,
      updateTime,
      filler,
    } = ctx.request.body;

    const results = await this.ctx.service.financial.updateFinancial(
      id,
      financialType,
      financialAddress,
      financialName,
      creatTime,
      invest,
      contactPerson,
      contactTel,
      contactEmail,
      description,
      updateTime,
      filler
    );
    ctx.body = new Result(results);
  }

  async createFinancial() {
    const { ctx } = this;
    await ctx.getFileStream().then(async r => {
      const {
        financialName,
        financialAddress,
        financialType,
        creatTime,
        invest,
        contactPerson,
        contactTel,
        contactEmail,
        description,
        updateTime,
        filler,
        financialCode,
      } = r.fields;
      const result = await this.ctx.service.financial.createFinancial(
        financialName,
        financialCode,
        financialAddress,
        financialType,
        creatTime,
        invest,
        contactPerson,
        contactEmail,
        contactTel,
        updateTime,
        filler,
        description,
        r
      );
      ctx.body = new Result(result);
    });
  }

  public async hasFile() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const res = await isExistObject(RoleEnum.ORGANIZATION, Number(id), ".pdf");
    if (res?.exist) {
      ctx.body = new Result(res, res.msg);
    } else {
      ctx.status = 404;
      ctx.body = new Result(res, res.msg);
    }
  }

  public async uploadFinancial() {
    const { ctx } = this;
    let OKnum = 0;
    let falseNUM = 0;
    await ctx.getFileStream().then(async r => {
      // 异步
      const newBuffer = await toArray(r).then(function (parts) {
        let buffers = [];
        for (let i = 0, l = parts.length; i < l; ++i) {
          let part = parts[i]
          buffers.push((part instanceof Buffer) ? part as never : new Buffer(part) as never)
        }
        return Buffer.concat(buffers);
      })
      const parse = xlsx.parse(newBuffer, {
        bookType: "xlsx",
        bookSST: false,
        type: "buffer",
      });
      console.log('parse:', parse);
      for (let i = 0; i < parse[0].data.length - 3; i++) {
        const data = parse[0].data.slice(3)[i];
        const result = await this.ctx.service.financial.createUploadFinancial(
          data[0],
          data[1],
          data[2],
          data[3],
          data[4],
          data[5],
          data[6],
          data[7],
          data[8],
          data[9],
          r.fields.username
        );
        if (result?.state === "true") {
          OKnum++;
        } else {
          falseNUM++;
        }
      }

      ctx.body = {
        true: OKnum,
        false: falseNUM,
      };
    });
  }
}
